#!/bin/bash
# Relationship Cockpit — Mac installer (.app entry point)
set -euo pipefail

# Resolve payload next to this binary: .../Contents/MacOS/install → .../Contents/Resources/payload
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONTENTS="$(cd "$SCRIPT_DIR/.." && pwd)"
PAYLOAD="$CONTENTS/Resources/payload"
WWW_SRC="$PAYLOAD/www"
COMP_SRC="$PAYLOAD/companion"

APP_SUPPORT="$HOME/Library/Application Support/RelationshipCockpit"
WWW="$APP_SUPPORT/www"
COMP="$APP_SUPPORT/companion"
APP_BUNDLE="$HOME/Applications/Relationship Cockpit Companion.app"
LAUNCH="$HOME/Library/LaunchAgents/com.relationshipcockpit.companion.plist"
LOGDIR="$HOME/Library/Logs/RelationshipCockpit"

# Detect Terminal vs double-clicked .app (no TTY → GUI dialogs)
IN_TERMINAL=0
if [ -t 0 ] && [ -t 1 ]; then
  IN_TERMINAL=1
fi

ui_info() {
  local msg="$1"
  if [ "$IN_TERMINAL" = "1" ]; then
    echo "$msg"
  fi
}

ui_error() {
  local msg="$1"
  if [ "$IN_TERMINAL" = "1" ]; then
    echo "ERROR: $msg" >&2
    read -r -p "Press Return to close…" _ || true
  else
    osascript -e "display dialog \"$msg\" with title \"Relationship Cockpit Installer\" buttons {\"OK\"} default button 1 with icon stop" >/dev/null 2>&1 || true
  fi
}

ui_success() {
  local msg="$1"
  if [ "$IN_TERMINAL" = "1" ]; then
    echo
    echo "$msg"
    read -r -p "Press Return to close…" _ || true
  else
    osascript -e "display dialog \"$msg\" with title \"Relationship Cockpit Installer\" buttons {\"OK\"} default button 1 with icon note" >/dev/null 2>&1 || true
  fi
}

ui_info "════════════════════════════════════════════"
ui_info "  Relationship Cockpit — Mac Live Sync"
ui_info "════════════════════════════════════════════"
ui_info ""

if [ ! -f "$WWW_SRC/index.html" ]; then
  ui_error "Installer payload/www is missing. Re-download Relationship-Cockpit-Mac-Installer.dmg (or .zip) and try again."
  exit 1
fi
if [ ! -f "$COMP_SRC/companion.py" ] || [ ! -f "$COMP_SRC/messages_lib.py" ]; then
  ui_error "Installer payload/companion is incomplete. Re-download the Mac installer and try again."
  exit 1
fi

mkdir -p "$HOME/Applications" "$APP_SUPPORT" "$LOGDIR" \
  "$APP_BUNDLE/Contents/MacOS" "$COMP" "$WWW"

ui_info "→ Installing companion…"
cp -f "$COMP_SRC/companion.py" "$COMP_SRC/messages_lib.py" "$COMP/"
chmod +x "$COMP/companion.py"

ui_info "→ Installing app files…"
if command -v rsync >/dev/null 2>&1; then
  rsync -a --delete "$WWW_SRC/" "$WWW/"
else
  rm -rf "$WWW"
  mkdir -p "$WWW"
  cp -R "$WWW_SRC/." "$WWW/"
fi

ui_info "→ Creating Companion.app…"
cat > "$APP_BUNDLE/Contents/Info.plist" << 'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleName</key><string>Relationship Cockpit Companion</string>
  <key>CFBundleDisplayName</key><string>Relationship Cockpit Companion</string>
  <key>CFBundleIdentifier</key><string>com.relationshipcockpit.companion</string>
  <key>CFBundleVersion</key><string>1.0</string>
  <key>CFBundleShortVersionString</key><string>1.0</string>
  <key>CFBundleExecutable</key><string>cockpit-companion</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>LSUIElement</key><true/>
</dict>
</plist>
PLIST

cat > "$APP_BUNDLE/Contents/MacOS/cockpit-companion" << 'BIN'
#!/bin/bash
export COCKPIT_WWW="${COCKPIT_WWW:-$HOME/Library/Application Support/RelationshipCockpit/www}"
export COCKPIT_PORT="${COCKPIT_PORT:-8788}"
COMP="$HOME/Library/Application Support/RelationshipCockpit/companion"
LOGDIR="$HOME/Library/Logs/RelationshipCockpit"
mkdir -p "$LOGDIR"
cd "$COMP" || exit 1
exec /usr/bin/python3 -u "$COMP/companion.py" >>"$LOGDIR/companion.stdout.log" 2>>"$LOGDIR/companion.stderr.log"
BIN
chmod +x "$APP_BUNDLE/Contents/MacOS/cockpit-companion"

ui_info "→ Installing LaunchAgent (python3 directly — FDA-safe)…"
cat > "$LAUNCH" << PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>com.relationshipcockpit.companion</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/python3</string>
    <string>-u</string>
    <string>$COMP/companion.py</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>WorkingDirectory</key><string>$COMP</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>COCKPIT_WWW</key><string>$WWW</string>
    <key>COCKPIT_PORT</key><string>8788</string>
  </dict>
  <key>StandardOutPath</key><string>$LOGDIR/companion.stdout.log</string>
  <key>StandardErrorPath</key><string>$LOGDIR/companion.stderr.log</string>
  <key>ProcessType</key><string>Background</string>
</dict>
</plist>
PLIST

launchctl bootout "gui/$(id -u)/com.relationshipcockpit.companion" 2>/dev/null || true
sleep 0.5
launchctl bootstrap "gui/$(id -u)" "$LAUNCH" 2>/dev/null || launchctl load "$LAUNCH"
launchctl kickstart -k "gui/$(id -u)/com.relationshipcockpit.companion" 2>/dev/null || true

ui_info "→ Waiting for companion…"
READY=0
for i in 1 2 3 4 5 6 7 8; do
  if curl -sf -m 2 "http://127.0.0.1:8788/api/health" >/dev/null 2>&1; then
    READY=1
    break
  fi
  sleep 0.75
done

if [ "$IN_TERMINAL" = "1" ]; then
  echo
  if [ "$READY" = "1" ]; then
    echo "Companion is up."
    echo "Pairing / health:"
    curl -sS -m 3 "http://127.0.0.1:8788/api/pairing" 2>/dev/null || true
    echo
  else
    echo "Companion is starting… open http://127.0.0.1:8788/ in a moment."
  fi
fi

open "http://127.0.0.1:8788/" 2>/dev/null || true

if [ "$IN_TERMINAL" = "1" ]; then
  echo
  echo "ONE-TIME (if chats look empty):"
  echo "  System Settings → Privacy & Security → Full Disk Access"
  echo "  Enable: /usr/bin/python3   (and/or Relationship Cockpit Companion.app)"
  echo "  Then: launchctl kickstart -k gui/\$(id -u)/com.relationshipcockpit.companion"
  echo
fi

/usr/bin/python3 - <<'PY'
import json, urllib.request, subprocess
try:
  d = json.load(urllib.request.urlopen("http://127.0.0.1:8788/api/health", timeout=3))
  fda = d.get("fda") or {}
  if not fda.get("ok"):
    subprocess.run(
      ["open", "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"],
      check=False,
    )
    print("Opened Full Disk Access — grant /usr/bin/python3, then kickstart.")
  else:
    print("Full Disk Access looks OK.")
except Exception as e:
  print("(health check deferred:", e, ")")
PY

SUCCESS_MSG="Install complete. Browser opened http://127.0.0.1:8788/

If chats look empty: System Settings → Privacy & Security → Full Disk Access → enable /usr/bin/python3 (and/or Relationship Cockpit Companion.app), then restart the companion.

Keep this Mac awake on the same Wi-Fi as your phone."

ui_success "$SUCCESS_MSG"
